<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

<script type="text/javascript" src="http://tajs.qq.com/stats?sId=64887707" charset="UTF-8"></script>



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">




  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />


















  
  
    
  
  <link href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.2/dist/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="kNN,Python," />








  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.2" />






<meta name="description" content="学习机器学习实战一书，记录一下。书上原代码都是以Python2版本编写，这边我是用Python3版本，所以会与书上代码有少许不同。">
<meta name="keywords" content="kNN,Python">
<meta property="og:type" content="article">
<meta property="og:title" content="k-近邻算法">
<meta property="og:url" content="https://asdfv1929.github.io/2018/01/28/MLA-kNN/index.html">
<meta property="og:site_name" content="asdfv1929 &#39;s Home">
<meta property="og:description" content="学习机器学习实战一书，记录一下。书上原代码都是以Python2版本编写，这边我是用Python3版本，所以会与书上代码有少许不同。">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2018-01-29T11:18:58.416Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="k-近邻算法">
<meta name="twitter:description" content="学习机器学习实战一书，记录一下。书上原代码都是以Python2版本编写，这边我是用Python3版本，所以会与书上代码有少许不同。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://asdfv1929.github.io/2018/01/28/MLA-kNN/"/>





  <title>k-近邻算法 | asdfv1929 's Home</title>

  









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">asdfv1929 's Home</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photos">
          <a href="/photos/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-image"></i> <br />
            
            Photos
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-links">
          <a href="/links/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-address-book"></i> <br />
            
            Links
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://asdfv1929.github.io/2018/01/28/MLA-kNN/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="asdfv1929">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/headpic.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="asdfv1929 's Home">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">k-近邻算法</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-01-28T16:15:22+08:00">
                2018-01-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习实战/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习实战</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/01/28/MLA-kNN/" class="leancloud_visitors" data-flag-title="k-近邻算法">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">Visitors&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>学习机器学习实战一书，记录一下。书上原代码都是以Python2版本编写，这边我是用Python3版本，所以会与书上代码有少许不同。<br><a id="more"></a></p>
<h1 id="k-近邻算法"><a href="#k-近邻算法" class="headerlink" title="k-近邻算法"></a>k-近邻算法</h1><p>简单地说，k-近邻算法采用测量不同特征值之间的距离方法来进行分类。</p>
<h2 id="优缺点"><a href="#优缺点" class="headerlink" title="优缺点"></a>优缺点</h2><p>优点：精度高、对异常值不敏感、无数据输入假定<br>缺点：计算复杂度高、空间复杂度高<br>适用数据范围：数值型和标称型</p>
<h2 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h2><p>存在一个样本数据集合，也称作训练样本集，并且样本集中每个数据都存在标签，即我们知道样本集中每一数据与所属分类的对应关系。输入没有标签的新数据后，将新数据的每个特征与样本集中数据对应的特征进行比较，然后算法提取样本集中特征最相似数据（最近邻）的分类标签。一般说来，我们只选择样本数据集中前<code>k</code>个最相似的数据，这就<code>k-近邻</code>算法中<code>k</code>的出处，通常<code>k</code>是不大于20的整数。最后选择<code>k</code>个最相似数据中出现次数最多的分类（投票规则），作为新数据的分类。</p>
<h2 id="一般流程"><a href="#一般流程" class="headerlink" title="一般流程"></a>一般流程</h2><ul>
<li>收集数据：可使用任何方法</li>
<li>准备数据：数据格式结构化处理</li>
<li>分析数据：任意选择方法</li>
<li>训练算法：此步骤不适用于k-近邻算法</li>
<li>测试算法：计算错误率</li>
<li>使用算法：首先输入样本数据和结构化的输出结果，然后运行k-近邻算法判定输入数据分别属于哪个分类，最后应用对计算出的分类执行后续的处理</li>
</ul>
<h2 id="导入数据"><a href="#导入数据" class="headerlink" title="导入数据"></a>导入数据</h2><p>新建Python文件<code>kNN.py</code>，添加数据导入函数：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">createDataSet</span><span class="params">()</span>:</span></div><div class="line">    group = np.array([[<span class="number">1.0</span>, <span class="number">1.1</span>], [<span class="number">1.0</span>, <span class="number">1.0</span>], [<span class="number">0</span>, <span class="number">0</span>], [<span class="number">0</span>, <span class="number">0.1</span>]])</div><div class="line">    labels = [<span class="string">'A'</span>, <span class="string">'A'</span>, <span class="string">'B'</span>, <span class="string">'B'</span>]</div><div class="line">    <span class="keyword">return</span> group, labels</div></pre></td></tr></table></figure></p>
<p>当然该函数中的四组数据及其标签均是人为假定的，后期可通过读取txt、csv等文件来获取数据。</p>
<h2 id="实现kNN算法"><a href="#实现kNN算法" class="headerlink" title="实现kNN算法"></a>实现kNN算法</h2><p>这边采用的是<code>欧氏距离</code>公式来计算两个向量点之间的距离，公式为：<br>$$<br>d (x_a, x_b) = \sqrt{\sum_{p} \left( x^p_a - x^p_b \right)^2}<br>$$<br>算法的伪代码实现：<br>对未知类别属性的数据集（测试集）中的每个点依次执行以下操作</p>
<ul>
<li>计算已知类别数据集（训练集）中的点与当前点之间的距离；</li>
<li>按照距离递增次序排序；</li>
<li>选取与当前点距离最小的k个点；</li>
<li>确定前k个点所在类别的出现频率；</li>
<li>返回前k个点出现频率最高的类别作为当前点的预测分类。</li>
</ul>
<p>Python代码实现：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># 分类器实现，参数：输入测试数据、训练集、训练标签、k值</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">classify</span><span class="params">(inX, dataSet, labels, k)</span>:</span></div><div class="line">    dataSetSize = dataSet.shape[<span class="number">0</span>]                      <span class="comment"># 数据集大小，即训练样本数量</span></div><div class="line">    diffMat = np.tile(inX, (dataSetSize, <span class="number">1</span>)) - dataSet  <span class="comment"># 计算两矩阵元素级别上的差</span></div><div class="line">    sqDiffMat = diffMat ** <span class="number">2</span>                            <span class="comment"># 所有元素求平方</span></div><div class="line">    sqDistances = sqDiffMat.sum(axis=<span class="number">1</span>)                 <span class="comment"># 横轴上所有元素求和   [ 2.21  2.    0.    0.01]</span></div><div class="line">    distances = sqDistances ** <span class="number">0.5</span>                      <span class="comment"># 开根号  [ 1.48660687  1.41421356  0.          0.1       ]</span></div><div class="line">    sortedDistIndicies = distances.argsort()            <span class="comment"># 从小到大排序后返回其索引 [2 3 1 0]</span></div><div class="line">    classCount = &#123;&#125;                                     <span class="comment"># 空字典，存储前k个数据的标签及其计数</span></div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(k):                                  <span class="comment"># 遍历距离最小的前k个，统计它们的标签数量</span></div><div class="line">        votelabel = labels[sortedDistIndicies[i]]       <span class="comment"># 依次获取该数据的标签</span></div><div class="line">        classCount[votelabel] = classCount.get(votelabel, <span class="number">0</span>) + <span class="number">1</span>  <span class="comment"># 若字典中存在该标签，则在该值上直接加1；若不存在，则先初始化为0，再加1</span></div><div class="line">    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(<span class="number">1</span>), reverse=<span class="keyword">True</span>)</div><div class="line">    <span class="keyword">return</span> sortedClassCount[<span class="number">0</span>][<span class="number">0</span>]                       <span class="comment"># 返回降序排序后数量最多的标签的值</span></div></pre></td></tr></table></figure></p>
<blockquote>
<p>注：</p>
<ol>
<li><code>dataSet.shape</code>返回的是一个<code>tuple</code>，里面有两个元素，简单来说就是数据集数组的行和列数，也就是数据集的样本数量和单个样本的特征数。</li>
<li><code>np.tile函数（import numpy as np）</code>：输入按照函数参数右侧的数值或元祖来进行复制扩充自己。<br>因此这边代码中<code>np.tile(inX, (dataSetSize, 1))</code>，实际上就是将<code>inX</code>整个数据在纵轴方向上复制扩充了<code>dataSetSize</code>倍，横轴方向上保持1倍，即不变。<br>这样使得原数据<code>inX</code>可以与数据集<code>dataSet</code>中每个样本进行相减求差值。</li>
<li><code>sqDiffMat.sum(axis=1)</code>：对<code>sqDiffMat</code>做求和操作，<code>axis=1</code>表示对列进行操作，但是是以横轴为方向（其实就是行上所有数求和）。所以这边做的是对测试样本与每个训练样本的差值的求和。若<code>axis=0</code>则表示对行进行操作，但是是以列为方向（列方向上所有数求和）。</li>
<li><code>sortedDistIndicies = distances.argsort()</code>：将<code>distances</code>中的元素从小到大排列，提取其对应的index(索引)，然后输出到<code>sortedDistIndicies</code>。</li>
<li><code>sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)</code>：<code>classCount.items()</code>返回的是一个列表，其中包含了由键值组成的元祖；<code>operator.itemgetter(1)</code>表示定义一个函数，获取第1个域；<code>reverse=True</code>表示逆序。所以整个<code>sorted()</code>函数做的是对<code>classCount.items()</code>这元祖列表做排序（逆序）操作，这排序的规则是按<code>key</code>来进行的，也就是根据列表中元祖的第1个域（即第2个值）来排序（其实就是根据各个标签的统计数量来降序排序）。</li>
</ol>
</blockquote>
<h2 id="测试分类器"><a href="#测试分类器" class="headerlink" title="测试分类器"></a>测试分类器</h2><p><code>错误率</code>是常用的评估方法，主要用于评估分类器在某个数据集上的执行效果。分类器的错误率：分类器给出的错误结果的次数除以测试执行的总数。完美分类器的错误率为0，最差分类器的错误率为1.0。</p>
<p>简单地调用运行：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> kNN</div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    group, labels = kNN.createDataSet()</div><div class="line">    label = kNN.classify([<span class="number">0</span>, <span class="number">0</span>], group, labels, <span class="number">3</span>)</div><div class="line">    print(label)</div></pre></td></tr></table></figure></p>
<h1 id="示例：使用k-近邻算法改进约会网站的配对效果"><a href="#示例：使用k-近邻算法改进约会网站的配对效果" class="headerlink" title="示例：使用k-近邻算法改进约会网站的配对效果"></a>示例：使用k-近邻算法改进约会网站的配对效果</h1><h2 id="准备数据"><a href="#准备数据" class="headerlink" title="准备数据"></a>准备数据</h2><p>数据文件：<code>datingTestSet2.txt</code>，每个样本（文件中每一行）中主要包含每一个对象的3种特征：每年获得的飞行常客里程数、玩视频游戏所耗时间百分比、每周消费的冰激凌公升数，最后一列是标签值：1、2、3，表示喜欢的程度。</p>
<p>在<code>kNN.py</code>文件中添加<code>file2matrix</code>函数，输入为文件名字符串，输出为训练样本矩阵和类标签向量。<br>代码如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">file2matrix</span><span class="params">(filename)</span>:</span></div><div class="line">    <span class="keyword">with</span> open(filename, <span class="string">'r'</span>) <span class="keyword">as</span> file:                        <span class="comment"># 打开文件</span></div><div class="line">        arrayLines = file.readlines()                        <span class="comment"># 读取文件中所有行数据</span></div><div class="line">        numberOfLines = len(arrayLines)                      <span class="comment"># 文件行数</span></div><div class="line">        returnMat = np.zeros((numberOfLines, <span class="number">3</span>))             <span class="comment"># 创建返回的矩阵，初始化为0</span></div><div class="line">        classLabelVector = []</div><div class="line">        index = <span class="number">0</span></div><div class="line">        <span class="keyword">for</span> line <span class="keyword">in</span> arrayLines:                              <span class="comment"># 遍历行</span></div><div class="line">            line = line.strip()                              <span class="comment"># 去除回车字符</span></div><div class="line">            listFromLine = line.split(<span class="string">'\t'</span>)                  <span class="comment"># 根据\t划分为列表</span></div><div class="line">            returnMat[index, :] = listFromLine[<span class="number">0</span>:<span class="number">3</span>]          <span class="comment"># 获取该行的前3个数据</span></div><div class="line">            classLabelVector.append(int(listFromLine[<span class="number">-1</span>]))   <span class="comment"># 获取该样本数据的标签值</span></div><div class="line">            index += <span class="number">1</span></div><div class="line">    <span class="keyword">return</span> returnMat, classLabelVector                       <span class="comment"># 返回样本数据数组和标签</span></div></pre></td></tr></table></figure></p>
<p>调用函数，并打印数据：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">dataArray, dataLabels = kNN.file2matrix(<span class="string">"datingTestSet2.txt"</span>)</div><div class="line">print(dataArray)</div><div class="line">print(dataLabels[:<span class="number">10</span>])</div></pre></td></tr></table></figure></p>
<p>数据打印显示为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">[[  4.09200000e+04   8.32697600e+00   9.53952000e-01]</div><div class="line"> [  1.44880000e+04   7.15346900e+00   1.67390400e+00]</div><div class="line"> [  2.60520000e+04   1.44187100e+00   8.05124000e-01]</div><div class="line"> ...</div><div class="line"> [  2.65750000e+04   1.06501020e+01   8.66627000e-01]</div><div class="line"> [  4.81110000e+04   9.13452800e+00   7.28045000e-01]</div><div class="line"> [  4.37570000e+04   7.88260100e+00   1.33244600e+00]]</div><div class="line">[3, 2, 1, 1, 1, 1, 3, 3, 1, 3]</div></pre></td></tr></table></figure></p>
<blockquote>
<p>注：</p>
<ol>
<li><code>np.zeros((a, b))</code>创建a行b列的数组，其值全为0</li>
<li><code>line.split(&#39;\t&#39;)</code>对字符串按<code>\t</code>做划分操作，得到由多个子字符串组成的列表</li>
</ol>
</blockquote>
<h2 id="归一化处理"><a href="#归一化处理" class="headerlink" title="归一化处理"></a>归一化处理</h2><p>因为特征属性<code>飞行常客里程数</code>的数值较大，直接使用欧氏距离的话该属性值会严重影响计算结果。</p>
<p>因此，在处理这种不同取值范围的特征值时，通常采用的方法是将<code>数值归一化</code>，如将取值范围处理为0~1或者-1~1之间。下面公式将任意取值范围的特征值转化为0~1区间内的值：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">newValue = (oldValue - min) / (max - min)</div></pre></td></tr></table></figure></p>
<p>其中<code>min</code>和<code>max</code>分别是数据集中的最小特征值和最大特征值。</p>
<p>在<code>kNN.py</code>中添加新函数<code>autoNorm()</code>，该函数自动将数字特征值转化为0~1的区间：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">autoNorm</span><span class="params">(dataSet)</span>:</span></div><div class="line">    minValues = dataSet.min(<span class="number">0</span>)                          <span class="comment"># 返回数据集中每列上的最小值</span></div><div class="line">    maxValues = dataSet.max(<span class="number">0</span>)                          <span class="comment"># 每列上的最大值</span></div><div class="line">    ranges = maxValues - minValues                      <span class="comment"># 求差，得数据的范围</span></div><div class="line">    normDataSet = np.zeros(shape=np.shape(dataSet))     <span class="comment"># 根据shape创建数组，全为0</span></div><div class="line">    m = dataSet.shape[<span class="number">0</span>]                                <span class="comment"># 样本数量</span></div><div class="line">    normDataSet = dataSet - np.tile(minValues, (m, <span class="number">1</span>))  <span class="comment"># 公式</span></div><div class="line">    normDataSet = normDataSet / np.tile(ranges, (m, <span class="number">1</span>))</div><div class="line">    <span class="keyword">return</span> normDataSet, ranges, minValues</div></pre></td></tr></table></figure></p>
<h2 id="测试算法"><a href="#测试算法" class="headerlink" title="测试算法"></a>测试算法</h2><p>在<code>kNN.py</code>中添加测试代码，作为完整程序来验证分类器：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">dataClassTest</span><span class="params">()</span>:</span></div><div class="line">    testRatio = <span class="number">0.20</span>                                          <span class="comment"># 定义数据集中为测试样本的比例</span></div><div class="line">    dataSet, dataLabels = file2matrix(<span class="string">"datingTestSet2.txt"</span>)   <span class="comment"># 读取数据</span></div><div class="line">    normMat, ranges, minValues = autoNorm(dataSet)            <span class="comment"># 归一化处理</span></div><div class="line">    m = normMat.shape[<span class="number">0</span>]                                      <span class="comment"># 样本数量</span></div><div class="line">    numTestVecs = int(m * testRatio)                          <span class="comment"># 确定测试样本的数量</span></div><div class="line">    errorCount = <span class="number">0.0</span>                                          <span class="comment"># 错误数量统计</span></div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(numTestVecs):</div><div class="line">        classifierResult = classify(normMat[i, :], normMat[numTestVecs:m, :], dataLabels[numTestVecs:m], <span class="number">3</span>)  <span class="comment"># 传入测试数据、训练集、训练标签、k值</span></div><div class="line">        print(<span class="string">"classify: %d, read answer: %d"</span> % (classifierResult, dataLabels[i]))</div><div class="line">        <span class="keyword">if</span> classifierResult != dataLabels[i]:                <span class="comment"># 如果预测不正确，则统计加1</span></div><div class="line">            errorCount += <span class="number">1</span></div><div class="line">    print(<span class="string">"total error rate is: %f"</span> % (errorCount / float(numTestVecs)))  <span class="comment"># 打印错误率</span></div></pre></td></tr></table></figure></p>
<p>执行结果显示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">classify: 3, read answer: 3</div><div class="line">classify: 2, read answer: 2</div><div class="line">...</div><div class="line">...</div><div class="line">classify: 2, read answer: 2</div><div class="line">classify: 3, read answer: 3</div><div class="line">classify: 2, read answer: 2</div><div class="line">total error rate is: 0.080000</div></pre></td></tr></table></figure></p>
<h2 id="构建完整系统"><a href="#构建完整系统" class="headerlink" title="构建完整系统"></a>构建完整系统</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">classifyPerson</span><span class="params">()</span>:</span></div><div class="line">    resultList = [<span class="string">'not at all'</span>, <span class="string">'in small doses'</span>, <span class="string">'in large doses'</span>]              <span class="comment"># 定义三种喜欢程度，对应数据集中标签 1,2,3</span></div><div class="line">    ffMiles = float(input(<span class="string">"frequent flier miles earned per year?"</span>))              <span class="comment"># 输入每年飞行里程数</span></div><div class="line">    percentTats = float(input(<span class="string">"percentage of time spent playing video games?"</span>))  <span class="comment"># 输入玩游戏所耗时间百分比</span></div><div class="line">    iceCream = float(input(<span class="string">"liters of ice cream consumed per week?"</span>))            <span class="comment"># 输入每周消费冰激凌公升数</span></div><div class="line">    dataArray, dataLabels = file2matrix(<span class="string">"datingTestSet2.txt"</span>)                    <span class="comment"># 从txt中获取训练数据</span></div><div class="line">    normMat, ranges, minVals = autoNorm(dataArray)                               <span class="comment"># 归一化处理</span></div><div class="line">    inArray = np.array([ffMiles, percentTats, iceCream])                         <span class="comment"># 对测试数据处理，整合成数组</span></div><div class="line">    normInArray = (inArray - minVals) / ranges                                   <span class="comment"># 对数据做归一化处理</span></div><div class="line">    classifyResult = classify(normInArray, normMat, dataLabels, <span class="number">3</span>)               <span class="comment"># 分类，k=3</span></div><div class="line">    print(<span class="string">"you will probably like this person: "</span>, resultList[classifyResult - <span class="number">1</span>])</div></pre></td></tr></table></figure>
<p>只要输入对应特征的值，就可以获得系统的结果判定，运行结果显示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">percentage of time spent playing video games?12</div><div class="line">frequent flier miles earned per year?30000</div><div class="line">liters of ice cream consumed per year?0.5</div><div class="line">you will probably like this person:  in large doses</div></pre></td></tr></table></figure></p>
<h1 id="示例：手写识别系统"><a href="#示例：手写识别系统" class="headerlink" title="示例：手写识别系统"></a>示例：手写识别系统</h1><h2 id="准备数据-1"><a href="#准备数据-1" class="headerlink" title="准备数据"></a>准备数据</h2><p>数字图像均已存储为txt形式，里面是由32行32列的0和1数字组成</p>
<p>首先把<code>32x32</code>的二进制图像转换为<code>1x1024</code>的向量，这样就可以用之前的分类器来处理这些数字图像信息了。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># 将图像转为向量</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">img2vector</span><span class="params">(filename)</span>:</span></div><div class="line">    returnVector = np.zeros((<span class="number">1</span>, <span class="number">1024</span>))                       <span class="comment"># 初始化0数组，1行1024列</span></div><div class="line">    <span class="keyword">with</span> open(filename, <span class="string">'r'</span>) <span class="keyword">as</span> file:                        <span class="comment"># 读取文件</span></div><div class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">32</span>):                                  <span class="comment"># 遍历行</span></div><div class="line">            lineStr = file.readline()                        <span class="comment"># 读取行</span></div><div class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">32</span>):                              <span class="comment"># 遍历列</span></div><div class="line">                returnVector[<span class="number">0</span>, <span class="number">32</span> * i + j] = int(lineStr[j])<span class="comment"># 将该行上第j个数据存进数组第i行第j列中</span></div><div class="line">    <span class="keyword">return</span> returnVector                                      <span class="comment"># 返回数组</span></div></pre></td></tr></table></figure></p>
<h2 id="测试算法-1"><a href="#测试算法-1" class="headerlink" title="测试算法"></a>测试算法</h2><p>上边我们已将数据处理为分类器可以识别的格式，现在我们将这些数据输入到分类器中，检测分类器的执行效果。</p>
<p><code>kNN.py</code>中需添加<code>from os import listdir</code>，用于列出给定目录的文件名。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">handwritingClassTest</span><span class="params">()</span>:</span></div><div class="line">    hwLabels = []                                        <span class="comment"># 列表，存放训练数据集标签</span></div><div class="line">    trainingFileList = listdir(<span class="string">"digits/trainingDigits"</span>)  <span class="comment"># 列出给定目录中的文件名</span></div><div class="line">    m = len(trainingFileList)                            <span class="comment"># 训练样本数</span></div><div class="line">    trainingMat = np.zeros((m, <span class="number">1024</span>))                    <span class="comment"># 初始化全0矩阵 m行1024列</span></div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(m):                                   <span class="comment"># 遍历训练数据</span></div><div class="line">        fileNameStr = trainingFileList[i]                <span class="comment"># 获取文件名全称，如 3_107.txt</span></div><div class="line">        fileStr = fileNameStr.split(<span class="string">'.'</span>)[<span class="number">0</span>]              <span class="comment"># 根据 . 划分，获取文件名 如 3_107</span></div><div class="line">        classNum = int(fileStr.split(<span class="string">'_'</span>)[<span class="number">0</span>])            <span class="comment"># 根据 _ 划分，获取该文件表示的真实数字 如 3</span></div><div class="line">        hwLabels.append(classNum)                        <span class="comment"># 将该数字标签放入训练集标签列表中</span></div><div class="line">        trainingMat[i, :] = img2vector(<span class="string">'digits/trainingDigits/%s'</span> % fileNameStr)  <span class="comment"># 调用函数，将第i个文件内的内容转化为数组，并存储</span></div><div class="line">    testFileList = listdir(<span class="string">"digits/testDigits"</span>)     <span class="comment"># 列出测试集目录中的文件名</span></div><div class="line">    errorCount = <span class="number">0.0</span>                                <span class="comment"># 错误统计</span></div><div class="line">    mTest = len(testFileList)                       <span class="comment"># 测试集大小</span></div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(mTest):                          <span class="comment"># 遍历测试集</span></div><div class="line">        fileNameStr = testFileList[i]</div><div class="line">        fileStr = fileNameStr.split(<span class="string">'.'</span>)[<span class="number">0</span>]</div><div class="line">        classNum = int(fileStr.split(<span class="string">'_'</span>)[<span class="number">0</span>])</div><div class="line">        vectorUnderTest = img2vector(<span class="string">"digits/testDigits/%s"</span> % fileNameStr)</div><div class="line">        classifyResult = classify(vectorUnderTest, trainingMat, hwLabels, <span class="number">3</span>)  <span class="comment"># 调用函数，预测数字</span></div><div class="line">        print(<span class="string">"the classifier: %d, the real value: %d"</span> % (classifyResult, classNum))</div><div class="line">        <span class="keyword">if</span> classifyResult != classNum:</div><div class="line">            errorCount += <span class="number">1.0</span></div><div class="line">    print(<span class="string">"total number of errors: %d"</span> % errorCount)</div><div class="line">    print(<span class="string">"total error rate: %f"</span> % (errorCount / float(mTest)))   <span class="comment"># 错误率</span></div></pre></td></tr></table></figure>
<p>调用运行：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">kNN.handwritingClassTest()</div></pre></td></tr></table></figure></p>
<p>结果显示：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">the classifier: <span class="number">0</span>, the real value: <span class="number">0</span></div><div class="line">the classifier: <span class="number">0</span>, the real value: <span class="number">0</span></div><div class="line">...</div><div class="line">the classifier: <span class="number">9</span>, the real value: <span class="number">9</span></div><div class="line">the classifier: <span class="number">9</span>, the real value: <span class="number">9</span></div><div class="line">the classifier: <span class="number">9</span>, the real value: <span class="number">9</span></div><div class="line">total number of errors: <span class="number">10</span></div><div class="line">total error rate: <span class="number">0.010571</span></div></pre></td></tr></table></figure></p>
<h1 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h1><p>本篇主要就是学习k-近邻算法，以及该算法的两个简单实际应用。k-近邻算法必须保存全部数据集，如果训练数据集很大，必须使用大量的存储空间。由于必须对数据集中的每个数据计算距离值，实际使用时非常耗时。</p>
<p>代码链接：<a href="https://github.com/asdfv1929/MachineLearningInAction_Python3/tree/master/Chapter02_kNN" target="_blank" rel="external">https://github.com/asdfv1929/MachineLearningInAction_Python3/tree/master/Chapter02_kNN</a></p>

      
    </div>
    
    
    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:22px;">------------- 本 文 结 束 <i class="fa fa-paw"></i> 感 谢 您 的 阅 读 -------------</div>
    
</div>

      
    </div>

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="asdfv1929 WeChat Pay"/>
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="asdfv1929 Alipay"/>
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>Post author:</strong>
    asdfv1929
  </li>
  <li class="post-copyright-link">
    <strong>Post link:</strong>
    <a href="https://asdfv1929.github.io/2018/01/28/MLA-kNN/" title="k-近邻算法">https://asdfv1929.github.io/2018/01/28/MLA-kNN/</a>
  </li>
  <li class="post-copyright-license">
    <strong>Copyright Notice: </strong>
    All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> unless stating additionally.
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/kNN/" rel="tag"><i class="fa fa-tag"></i> kNN</a>
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/28/add-the-end/" rel="next" title="Hexo NexT主题内给每篇文章后添加结束标语">
                <i class="fa fa-chevron-left"></i> Hexo NexT主题内给每篇文章后添加结束标语
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/02/16/happy-dog-year-2018/" rel="prev" title="狗年大吉！">
                狗年大吉！ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="gitalk-container"></div>

    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/images/headpic.jpg"
              alt="asdfv1929" />
          
            <p class="site-author-name" itemprop="name">asdfv1929</p>
            <p class="site-description motion-element" itemprop="description"></p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">46</span>
                <span class="site-state-item-name">posts</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">57</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/asdfv1929" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:asdfv1929@163.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://blog.csdn.net/tianlong1929" target="_blank" title="CSDN">
                  
                    <i class="fa fa-fw fa-contao"></i>CSDN</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://music.163.com/#/user/home?id=82875310" target="_blank" title="CloudMusic">
                  
                    <i class="fa fa-fw fa-music"></i>CloudMusic</a>
              </span>
            
          
        </div>


        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://zhengmengping.github.io/" title="Healer" target="_blank">Healer</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.hawky.me/" title="Hawky" target="_blank">Hawky</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://chentao.space/" title="Jack Chen" target="_blank">Jack Chen</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://morefox.net/" title="MOREFOX" target="_blank">MOREFOX</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://inspurer.github.io/" title="月小水长" target="_blank">月小水长</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.newt.fun/" title="不羁的脸闪着青涩" target="_blank">不羁的脸闪着青涩</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://stellarkey.github.io/" title="思维之海" target="_blank">思维之海</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://liujunzhou.top/" title="刘俊周" target="_blank">刘俊周</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://anlan.club/" title="Anlance" target="_blank">Anlance</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://iseexuhs.github.io/" title="ISEEX" target="_blank">ISEEX</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://fanlinxi.cn/" title="無曦" target="_blank">無曦</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.pandashen.com/" title="PandaShen" target="_blank">PandaShen</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.fujishiro.cn/" title="FujishiroOtone" target="_blank">FujishiroOtone</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://pengtuo.tech/" title="PeTu" target="_blank">PeTu</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yizibi.github.io/" title="一之笔" target="_blank">一之笔</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.wliwu.com/" title="WeiJiang1996" target="_blank">WeiJiang1996</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.luameows.wang/" title="Lumo's blog" target="_blank">Lumo's blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.cfzhao.com/" title="ZhaoYuwei's Blog" target="_blank">ZhaoYuwei's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://error666.github.io/" title="☆＼(￣ー￣)／☆" target="_blank">☆＼(￣ー￣)／☆</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://drew233.github.io/" title="Uncle_drew" target="_blank">Uncle_drew</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://ladies.ren/" title="易山博客" target="_blank">易山博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="宇宙湾" target="_blank">宇宙湾</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://chenfeiyang.top/" title="Feiyang Chen" target="_blank">Feiyang Chen</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#k-近邻算法"><span class="nav-number">1.</span> <span class="nav-text">k-近邻算法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#优缺点"><span class="nav-number">1.1.</span> <span class="nav-text">优缺点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#工作原理"><span class="nav-number">1.2.</span> <span class="nav-text">工作原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一般流程"><span class="nav-number">1.3.</span> <span class="nav-text">一般流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#导入数据"><span class="nav-number">1.4.</span> <span class="nav-text">导入数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现kNN算法"><span class="nav-number">1.5.</span> <span class="nav-text">实现kNN算法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试分类器"><span class="nav-number">1.6.</span> <span class="nav-text">测试分类器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#示例：使用k-近邻算法改进约会网站的配对效果"><span class="nav-number">2.</span> <span class="nav-text">示例：使用k-近邻算法改进约会网站的配对效果</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#准备数据"><span class="nav-number">2.1.</span> <span class="nav-text">准备数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#归一化处理"><span class="nav-number">2.2.</span> <span class="nav-text">归一化处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试算法"><span class="nav-number">2.3.</span> <span class="nav-text">测试算法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#构建完整系统"><span class="nav-number">2.4.</span> <span class="nav-text">构建完整系统</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#示例：手写识别系统"><span class="nav-number">3.</span> <span class="nav-text">示例：手写识别系统</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#准备数据-1"><span class="nav-number">3.1.</span> <span class="nav-text">准备数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试算法-1"><span class="nav-number">3.2.</span> <span class="nav-text">测试算法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#小结"><span class="nav-number">4.</span> <span class="nav-text">小结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">asdfv1929</span>

  
</div>

<!-- 
  <div class="powered-by">Powered by <a class="theme-link" href="https://hexo.io">Hexo</a></div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">Theme &mdash; <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.2</div>

 -->

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>





  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=64887707";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-beta.2/lazyload.js"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.2/dist/jquery.fancybox.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">

  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '5fe36b6fb87ecd8e46f4',
          clientSecret: '075b050ff7b5e6277fe683d300504bfa5e49037c',
          repo: 'asdfv1929.github.io',
          owner: 'asdfv1929',
          admin: ['asdfv1929'],
          id: location.pathname,
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')
       </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("l2qrG4ju8kp00y3c2cI8tg1y-gzGzoHsz", "LlxAjmFDL6zNzpRAP0cXqfA6");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>

<!--崩溃欺骗-->
<script type="text/javascript" src="/js/src/titleqipian.js"></script>


<script type="text/javascript" src="https://unpkg.com/minigrid@3.1.1/dist/minigrid.min.js"></script>

<link rel="stylesheet" href="/photos/photos.css">
<script type="text/javascript" src="/photos/photo.js"></script>
